package com.teleca.jamendo.ui.activity;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.gesture.GestureOverlayView;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.teleca.jamendo.JamendoApplication;
import com.teleca.jamendo.R;
import com.teleca.jamendo.api.JamendoGet2Api;
import com.teleca.jamendo.api.Playlist;
import com.teleca.jamendo.api.WSError;
import com.teleca.jamendo.api.impl.JamendoGet2ApiImpl;
import com.teleca.jamendo.db.DatabaseImpl;
import com.teleca.jamendo.dialog.AboutDialog;
import com.teleca.jamendo.mode.Album;
import com.teleca.jamendo.mode.PlaylistEntry;
import com.teleca.jamendo.mode.PlaylistRemote;
import com.teleca.jamendo.mode.Radio;
import com.teleca.jamendo.mode.Track;
import com.teleca.jamendo.ui.BaseActivity;
import com.teleca.jamendo.ui.activity.BrowsePlaylistActivity.Mode;
import com.teleca.jamendo.ui.adapter.AlbumAdapter;
import com.teleca.jamendo.ui.adapter.HomePagerAdapter;
import com.teleca.jamendo.ui.adapter.PlaylistRemoteAdapter;
import com.teleca.jamendo.ui.adapter.PurpleAdapter;
import com.teleca.jamendo.ui.adapter.PurpleEntry;
import com.teleca.jamendo.ui.adapter.PurpleListener;
import com.teleca.jamendo.ui.adapter.RadioAdapter;
import com.teleca.jamendo.ui.widget.LoadingUpView;
import com.teleca.jamendo.ui.widget.OnAlbumClickListener;

/**
 * 
 * @ClassName: HomeActivity
 * @Description: 应用主页
 * @author zou.sq
 * @date 2013-5-30 下午3:40:11
 * 
 */
public class HomeActivity extends BaseActivity implements OnAlbumClickListener, OnPageChangeListener, OnClickListener {

	private static final String TAG = "HomeActivity";

	private static enum SearchMode {
		Artist, Tag, UserPlaylist, UserStarredAlbums
	};

	private static int[] recommended_ids = { 9, // rock
			4, // dance
			5, // hiphop
			6, // jazz
			7, // lounge
			8, // pop
			283 // metal
	};

	private ViewPager mViewPager;

	private GridView mGvHome;
	private ImageView mIvCursor;
	private int currIndex = 0;// 当前页卡编号

	private TextView mTvTableMy;
	private TextView mTvTableSearch;
	private TextView mTvTableRadio;

	private int mCousorWidth;// 动画图片宽度
	private int mOffset = 0;// 动画图片偏移量
	private PurpleAdapter mHomePurpleAdapter;
	private GestureOverlayView mMainGestureView;
	private LoadingUpView mLoadingUpView;
	private List<View> mListViews;
	private Activity mActivity;
	private View mMainView;
	private View mSearchView;
	private View mRadioView;

	// Search
	private Spinner mSearchSpinner;
	private GridView mSearchListView;
	private EditText mSearchEditText;
	private Button mSearchButton;
	private GestureOverlayView mSearchGestureView;
	private PlaylistRemote[] mPlaylistRemotes = null;
	private SearchMode mSearchMode;

	// Radio
	private Radio[] mRecommendedRadios;
	private GridView mRadioListView;
	private RadioAdapter mRadioAdapter;
	private Button mButton;
	private EditText mEditText;
	private Spinner mRadioSpinner;
	private GestureOverlayView mRadioGestureView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_page);
		initVariables();
		initViews();
		setListener();
	}

	private void setListener() {
		mButton.setOnClickListener(this);
		mSearchButton.setOnClickListener(this);
		mTvTableMy.setOnClickListener(this);
		mTvTableSearch.setOnClickListener(this);
		mTvTableRadio.setOnClickListener(this);
		mRadioListView.setOnItemClickListener(mRadioListListener);
		mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
		mMainGestureView.addOnGesturePerformedListener(JamendoApplication.getInstance().getPlayerGestureHandler());
		mSearchGestureView.addOnGesturePerformedListener(JamendoApplication.getInstance().getPlayerGestureHandler());
		mRadioGestureView.addOnGesturePerformedListener(JamendoApplication.getInstance().getPlayerGestureHandler());
	}

	private void initVariables() {
		mActivity = this;
		mRecommendedRadios = new Radio[0];
		mListViews = new ArrayList<View>();
		mRadioAdapter = new RadioAdapter(this);
		mLoadingUpView = new LoadingUpView(this, true);
		mMainView = LayoutInflater.from(mActivity).inflate(R.layout.main, null);
		mSearchView = LayoutInflater.from(mActivity).inflate(R.layout.search, null);
		mRadioView = LayoutInflater.from(mActivity).inflate(R.layout.radio, null);
		mListViews.add(mMainView);
		mListViews.add(mSearchView);
		mListViews.add(mRadioView);
	}

	private void initViews() {
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mViewPager.setPageMarginDrawable(null);
		mViewPager.setAdapter(new HomePagerAdapter(mListViews));
		mIvCursor = (ImageView) findViewById(R.id.iv_cursor);
		mTvTableMy = (TextView) findViewById(R.id.tv_table_my);
		mTvTableSearch = (TextView) findViewById(R.id.tv_table_search);
		mTvTableRadio = (TextView) findViewById(R.id.tv_table_radio);

		initCousor();
		// 主页视图
		mGvHome = (GridView) mMainView.findViewById(R.id.HomeListView1);
		mMainGestureView = (GestureOverlayView) mMainView.findViewById(R.id.gestures);

		// 搜索视图
		mSearchButton = (Button) mSearchView.findViewById(R.id.btn_search);
		mSearchEditText = (EditText) mSearchView.findViewById(R.id.et_search);
		mSearchListView = (GridView) mSearchView.findViewById(R.id.gv_searcher);
		mSearchSpinner = (Spinner) mSearchView.findViewById(R.id.search_spinner);
		mSearchGestureView = (GestureOverlayView) mSearchView.findViewById(R.id.search_gestures);

		ArrayAdapter<CharSequence> reserchAdapter = ArrayAdapter.createFromResource(this, R.array.search_modes,
				android.R.layout.simple_spinner_item);
		reserchAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSearchSpinner.setAdapter(reserchAdapter);

		// 收音机视图
		mButton = (Button) mRadioView.findViewById(R.id.btn_radio_search);
		mEditText = (EditText) mRadioView.findViewById(R.id.et_radio_search);
		mRadioSpinner = (Spinner) mRadioView.findViewById(R.id.radio_spinner);
		mRadioListView = (GridView) mRadioView.findViewById(R.id.gv_radio_searcher);

		mRadioListView.setAdapter(mRadioAdapter);
		mButton.setText(R.string.radio);
		mEditText.setHint(R.string.radio_hint);

		ArrayAdapter<CharSequence> radioAdapter = ArrayAdapter.createFromResource(this, R.array.radio_modes,
				android.R.layout.simple_spinner_item);
		radioAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mRadioSpinner.setAdapter(radioAdapter);

		mRadioSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
				switch (position) {
					case 0:
						mRadioAdapter.setList(new DatabaseImpl(mActivity).getRecentRadios(20));
						break;
					case 1:
						new RadioLoadingAsyncTask().execute();
						break;
					default:
						break;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		mRadioGestureView = (GestureOverlayView) mRadioView.findViewById(R.id.radio_gestures);
	}

	private void initCousor() {
		mCousorWidth = BitmapFactory.decodeResource(getResources(), R.drawable.viewpager_tabicon).getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		mOffset = (screenW / 3 - mCousorWidth) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(mOffset, 0);
		mIvCursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = mOffset * 2 + mCousorWidth;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
				case 0:
					if (currIndex == 1) {
						animation = new TranslateAnimation(one, 0, 0, 0);
					} else if (currIndex == 2) {
						animation = new TranslateAnimation(two, 0, 0, 0);
					}
					break;
				case 1:
					if (currIndex == 0) {
						animation = new TranslateAnimation(mOffset, one, 0, 0);
					} else if (currIndex == 2) {
						animation = new TranslateAnimation(two, one, 0, 0);
					}
					break;
				case 2:
					if (currIndex == 0) {
						animation = new TranslateAnimation(mOffset, two, 0, 0);
					} else if (currIndex == 1) {
						animation = new TranslateAnimation(one, two, 0, 0);
					}
					break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			mIvCursor.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public void onAlbumClicked(Album album) {
		PlayerActivity.launch(this, album);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.home, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (JamendoApplication.getInstance().getPlayerEngineInterface() == null
				|| JamendoApplication.getInstance().getPlayerEngineInterface().getPlaylist() == null) {
			menu.findItem(R.id.player_menu_item).setVisible(false);
		} else {
			menu.findItem(R.id.player_menu_item).setVisible(true);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

			case R.id.player_menu_item:
				PlayerActivity.launch(this, (Playlist) null);
				break;

			case R.id.about_menu_item:
				new AboutDialog(this).show();
				break;

			case R.id.settings_menu_item:
				SettingsActivity.launch(this);
				break;

			default:

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			mGvHome.setSelection(1);
			PurpleEntry entry = (PurpleEntry) mGvHome.getAdapter().getItem(1);
			entry.getListener().performAction();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		fillHomeGridView();
		boolean gesturesEnabled = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("gestures", true);
		mMainGestureView.setEnabled(gesturesEnabled);
		super.onResume();
	}

	private void fillHomeGridView() {
		mHomePurpleAdapter = new PurpleAdapter(this);
		ArrayList<PurpleEntry> homeGridViewEntry = new ArrayList<PurpleEntry>();

		homeGridViewEntry.add(new PurpleEntry(R.drawable.list_cd, R.string.popular_albums_week, new PurpleListener() {
			@Override
			public void performAction() {
				startActivity(new Intent(HomeActivity.this, PopularAlbumsWeek.class));
			}
		}));

		homeGridViewEntry.add(new PurpleEntry(R.drawable.list_top, R.string.most_listened, new PurpleListener() {
			@Override
			public void performAction() {
				new Top100Task().execute();
			}
		}));

		homeGridViewEntry.add(new PurpleEntry(R.drawable.list_playlist, R.string.playlists, new PurpleListener() {
			@Override
			public void performAction() {
				BrowsePlaylistActivity.launch(HomeActivity.this, Mode.Normal);
			}
		}));

		final String userName = PreferenceManager.getDefaultSharedPreferences(this).getString("user_name", null);
		if (userName != null && userName.length() > 0) {
			homeGridViewEntry.add(new PurpleEntry(R.drawable.list_cd, R.string.albums, new PurpleListener() {
				@Override
				public void performAction() {
					StarredAlbumsActivity.launch(HomeActivity.this, userName);
				}
			}));
		}

		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			homeGridViewEntry.add(new PurpleEntry(R.drawable.list_download, R.string.download, new PurpleListener() {
				@Override
				public void performAction() {
					DownloadActivity.launch(HomeActivity.this);
				}
			}));
		}

		mHomePurpleAdapter.setList(homeGridViewEntry);
		mGvHome.setAdapter(mHomePurpleAdapter);
		mGvHome.setOnItemClickListener(mHomeItemClickListener);
	}

	/**
	 * Launches menu actions
	 */
	private OnItemClickListener mHomeItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int index, long time) {
			try {
				PurpleListener listener = ((PurpleEntry) adapterView.getAdapter().getItem(index)).getListener();
				if (listener != null) {
					listener.performAction();
				}
			} catch (ClassCastException e) {
				Log.w(TAG, "Unexpected position number was occurred");
			}
		}
	};

	private class Top100Task extends AsyncTask<Void, WSError, Playlist> {

		@Override
		public void onPreExecute() {
			super.onPreExecute();
			if (null != mLoadingUpView && !mLoadingUpView.isShowing()) {
				mLoadingUpView.showPopup(HomeActivity.this.getString(R.string.loading_top100));
			}
		}

		@Override
		public void onPostExecute(Playlist playlist) {
			if (null != mLoadingUpView && mLoadingUpView.isShowing()) {
				mLoadingUpView.dismiss();
			}
			if (null == playlist) {
				toast((String) getResources().getText(R.string.net_work_eror));
				return;
			} else {
				if (playlist.size() <= 0) {
					toast((String) getResources().getText(R.string.top100_fail));
					return;
				}
			}

			PlayerActivity.launch(HomeActivity.this, playlist);
			super.onPostExecute(playlist);
		}

		@Override
		protected Playlist doInBackground(Void... params) {
			JamendoGet2Api server = new JamendoGet2ApiImpl();
			int[] id = null;
			try {
				id = server.getTop100Listened();
				// if loading rss failed and no tracks are there - report an
				// error
				if (id == null) {
					toast((String) getResources().getText(R.string.top100_fail));
					return null;
				}
				List<Album> albums = server.getAlbumsByTracksId(id);
				Track[] tracks = server.getTracksByTracksId(id, JamendoApplication.getInstance().getStreamEncoding());
				if (albums == null || tracks == null)
					return null;
				Hashtable<Integer, PlaylistEntry> hashtable = new Hashtable<Integer, PlaylistEntry>();
				for (int i = 0; i < tracks.length; i++) {
					PlaylistEntry playlistEntry = new PlaylistEntry();
					playlistEntry.setAlbum(albums.get(i));
					playlistEntry.setTrack(tracks[i]);
					hashtable.put(tracks[i].getId(), playlistEntry);
				}

				// creating playlist in the correct order
				Playlist playlist = new Playlist();
				for (int i = 0; i < id.length; i++) {
					playlist.addPlaylistEntry(hashtable.get(id[i]));
				}
				return playlist;
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (WSError e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		mSearchMode = (SearchMode) savedInstanceState.getSerializable("mode");
		if (mSearchMode != null) {
			if (mSearchMode.equals(SearchMode.Artist) || mSearchMode.equals(SearchMode.Tag)
					|| mSearchMode.equals(SearchMode.UserStarredAlbums)) {
				AlbumAdapter adapter = new AlbumAdapter(this);
				adapter.setList((ArrayList<Album>) savedInstanceState.get("values"));
				mSearchListView.setAdapter(adapter);
				mSearchListView.setOnItemClickListener(mAlbumClickListener);
			}

			if (mSearchMode.equals(SearchMode.UserPlaylist)) {
				PlaylistRemoteAdapter adapter = new PlaylistRemoteAdapter(this);
				adapter.setList((ArrayList<PlaylistRemote>) savedInstanceState.get("values"));
				mSearchListView.setAdapter(adapter);
				mSearchListView.setOnItemClickListener(mPlaylistClickListener);
			}

		}
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (mSearchMode != null) {
			outState.putSerializable("mode", mSearchMode);
			if (mSearchMode.equals(SearchMode.Artist) || mSearchMode.equals(SearchMode.Tag)
					|| mSearchMode.equals(SearchMode.UserStarredAlbums)) {
				AlbumAdapter adapter = (AlbumAdapter) mSearchListView.getAdapter();
				outState.putSerializable("values", adapter.getList());
			}

			if (mSearchMode.equals(SearchMode.UserPlaylist)) {
				PlaylistRemoteAdapter adapter = (PlaylistRemoteAdapter) mSearchListView.getAdapter();
				outState.putSerializable("values", adapter.getList());
			}

		}
		super.onSaveInstanceState(outState);
	}

	private OnItemClickListener mAlbumClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int position, long time) {
			Album album = (Album) adapterView.getItemAtPosition(position);
			PlayerActivity.launch(mActivity, album);
		}
	};

	private OnItemClickListener mPlaylistClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
			PlaylistRemote playlistRemote = (PlaylistRemote) adapterView.getItemAtPosition(position);
			PlayerActivity.launch(mActivity, playlistRemote);
		}
	};

	private class SearchingAsyncTask extends AsyncTask<Integer, Integer, Integer> {

		private Integer mSearchMode;
		private BaseAdapter mAdapter;

		public SearchingAsyncTask(Integer mSearchMode) {
			super();
			this.mSearchMode = mSearchMode;
		}

		@Override
		public void onPreExecute() {
			super.onPreExecute();
			if (null != mLoadingUpView && !mLoadingUpView.isShowing()) {
				mLoadingUpView.showPopup(mActivity.getString(R.string.searching));
			}
		}

		@Override
		public Integer doInBackground(Integer... params) {
			switch (mSearchMode) {
				case 0:
					// artist search
					albumSearch(0);
					break;
				case 1:
					// tag search
					albumSearch(1);
					break;
				case 2:
					// playlist search
					playlistSearch();
					break;
				case 3:
					// starred album search
					albumSearch(3);
					break;
				default:
			}
			return mSearchMode;
		}

		@Override
		public void onPostExecute(Integer mode) {
			if (null != mLoadingUpView && mLoadingUpView.isShowing()) {
				mLoadingUpView.dismiss();
			}

			mSearchListView.setAdapter(mAdapter);

			// results are albums
			if (mode.equals(0) || mode.equals(1) || mode.equals(3)) {
				mSearchListView.setOnItemClickListener(mAlbumClickListener);
			}

			// results are playlists
			if (mode.equals(2)) {
				mSearchListView.setOnItemClickListener(mPlaylistClickListener);
			}
		}

		private void albumSearch(int id) {
			JamendoGet2Api service = new JamendoGet2ApiImpl();
			String query = mSearchEditText.getText().toString();
			List<Album> albums = null;
			try {
				switch (id) {
					case 0:
						albums = service.searchForAlbumsByArtist(query);
						HomeActivity.this.mSearchMode = SearchMode.Artist;
						break;
					case 1:
						albums = service.searchForAlbumsByTag(query);
						HomeActivity.this.mSearchMode = SearchMode.Tag;
						break;
					case 3:
						albums = service.getUserStarredAlbums(query);
						HomeActivity.this.mSearchMode = SearchMode.UserStarredAlbums;
						break;

					default:
						return;
				}

				AlbumAdapter albumAdapter = new AlbumAdapter(HomeActivity.this);
				albumAdapter.setList((ArrayList<Album>) albums);
				// albumAdapter.setListView(mSearchListView);
				mAdapter = albumAdapter;

			} catch (JSONException e) {
				e.printStackTrace();
			} catch (WSError e) {
				this.cancel(true);
			}
		}

		private void playlistSearch() {
			JamendoGet2Api service = new JamendoGet2ApiImpl();
			String user = mSearchEditText.getText().toString();
			try {
				mPlaylistRemotes = service.getUserPlaylist(user);
				if (mPlaylistRemotes != null) {
					PlaylistRemoteAdapter purpleAdapter = new PlaylistRemoteAdapter(mActivity);
					purpleAdapter.setList(mPlaylistRemotes);
					mAdapter = purpleAdapter;
					HomeActivity.this.mSearchMode = SearchMode.UserPlaylist;
				}

			} catch (JSONException e) {
				e.printStackTrace();
			} catch (WSError e) {
				this.cancel(true);
			}
		}
	}

	private class RadioLoadingAsyncTask extends AsyncTask<Void, WSError, Boolean> {

		@Override
		public void onPreExecute() {
			super.onPreExecute();
			if (null != mLoadingUpView && !mLoadingUpView.isShowing()) {
				mLoadingUpView.showPopup(mActivity.getString(R.string.loading_recomended_radios));
			}
		}

		@Override
		public Boolean doInBackground(Void... params) {
			try {
				loadRecommendedRadios();
				if (mRecommendedRadios == null || mRecommendedRadios.length == 0) {
					return false;
				} else {
					return true;
				}
			} catch (WSError e) {
				e.printStackTrace();
				return false;
			}
		}

		@Override
		public void onPostExecute(Boolean isSuccess) {
			if (null != mLoadingUpView && mLoadingUpView.isShowing()) {
				mLoadingUpView.dismiss();
			}
			if (isSuccess) {
				if (mRadioSpinner.getSelectedItemPosition() == 1) {
					mRadioAdapter.setList(mRecommendedRadios);
				}
			} else {
				toast(mActivity.getString(R.string.failed_recomended_radios));
				return;
			}
			super.onPostExecute(isSuccess);
		}

		@Override
		protected void onProgressUpdate(WSError... values) {
			Toast.makeText(mActivity, values[0].getMessage(), Toast.LENGTH_LONG).show();
			super.onProgressUpdate(values);
		}
	}

	private OnItemClickListener mRadioListListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			Radio radio = (Radio) mRadioAdapter.getItem(position);
			try {
				Playlist playlist = new JamendoGet2ApiImpl().getRadioPlaylist(radio, 20, JamendoApplication
						.getInstance().getStreamEncoding());
				new DatabaseImpl(mActivity).addRadioToRecent(radio);
				PlayerActivity.launch(mActivity, playlist);
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (WSError e) {
				Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
	};

	private void loadRecommendedRadios() throws WSError {
		try {
			mRecommendedRadios = new JamendoGet2ApiImpl().getRadiosByIds(recommended_ids);
		} catch (JSONException e) {
			mRecommendedRadios = new Radio[0];
			e.printStackTrace();
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		switch (arg0) {
			case 0:
				break;
			case 1:
				break;
			case 2:
				new RadioLoadingAsyncTask().execute();
				break;
			default:
				break;
		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
			case R.id.tv_table_my:
				mViewPager.setCurrentItem(0);
				break;
			case R.id.tv_table_search:
				mViewPager.setCurrentItem(1);
				break;
			case R.id.tv_table_radio:
				mViewPager.setCurrentItem(2);
				break;
			case R.id.btn_search:
				new SearchingAsyncTask(mSearchSpinner.getSelectedItemPosition()).execute();
				break;
			case R.id.btn_radio_search:
				doRadioButtonAction();
				break;
			default:
				break;
		}
	}

	private void doRadioButtonAction() {
		if (mEditText.getText().toString().length() == 0)
			return;
		int id = 0;
		String idstr = null;
		try {
			id = Integer.parseInt(mEditText.getText().toString()); // search
																	// by id
		} catch (NumberFormatException e) {
			idstr = mEditText.getText().toString(); // search by name
		}

		Radio[] radio = null;
		try {
			JamendoGet2Api service = new JamendoGet2ApiImpl();
			if (idstr == null && id > 0) {
				int[] ids = { id };
				radio = service.getRadiosByIds(ids);
			} else if (idstr != null) {
				radio = service.getRadiosByIdstr(idstr);
			}
			mRadioAdapter.setList(radio);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (WSError e) {
			Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_LONG).show();
			finish();
		}
	}

}
